<template>
	<div>
		<Card :bordered="false" dis-hover class="ivu-mt pt10">
			<Form ref="formValidate" :model="formValidate" :label-width="labelWidth" :label-position="labelPosition">
				<Row type="flex" :gutter="24" style="margin-left: 20px;">
					<!-- <Col>
						<FormItem label="时间选择：">
						  <DatePicker
						    :editable="false"
						    @on-change="onchangeTime"
						    :value="timeVal"
						    format="yyyy/MM/dd"
						   type="datetimerange"
						  placement="bottom-start"
						  placeholder="自定义时间"
						  class="input-width"
						  :options="options"
						  ></DatePicker>
						</FormItem>
					</Col> -->
					<Col>
					<FormItem :label="$t('page.stock.status')+'：'">
						<Select v-model="formValidate.status" :placeholder="$t('page.customer.please_select')" clearable @on-change="search"
							class="input-add">
							<Option value="0">{{$t('page.customer.not_received')}}</Option>
							<Option value="1">{{$t('page.customer.feedback_provided')}}</Option>
							<Option value="2">{{$t('page.customer.no_received')}}</Option>
						</Select>
					</FormItem>
					</Col>
					<Col>
					<FormItem :label="$t('page.customer.customer_name')+'：'">
						<Input enter-button style="width:300px" :placeholder="$t('page.customer.input_customer')"
							v-model="formValidate.customer_name" />
					</FormItem>

					</Col>
					<Col>
					<Button type="primary" @click="search" icon="md-search"></Button>
					</Col>

				</Row>
			</Form>
		</Card>

		<Card :bordered="false" dis-hover class="ive-mt tablebox">
			<div class="btnbox"></div>
			<div class="table">
				<Button type="primary" @click="openNewModal(0)">{{$t('page.customer.add_customer')}}</Button>
				<Table ref="table" :columns="columns" :data="tableList" class="ivu-mt" :loading="loading"
					no-data-text="暂无数据" no-filtered-data-text="暂无筛选结果" max-height="550">

					<template slot-scope="{ row, index }" slot="status">
						<span v-if="row.status == 1">{{$t('page.customer.feedback_provided')}}</span>
						<span v-else-if="row.status == 2">{{$t('page.customer.no_received')}}</span>
						<span v-else>{{$t('page.customer.not_received')}}</span>
					</template>
					<template slot-scope="{ row, index }" slot="action">
						<a v-if="row.status <= 0" @click="openNewModal(row.id)">{{$t('page.product.edit')}}</a>
						<Divider v-if="row.status <= 0" type="vertical" />
						<a v-if="row.status <= 0"
							@click="del(row, 'Cancel reception', index)">{{$t('page.product.cancel')}}</a>
						<Divider v-if="row.status <= 0" type="vertical" />
						<a @click="openDetailModal(row.id)">{{$t('page.order.detail')}}</a>
					</template>

					<!-- <template slot-scope="{ row, index }" slot="action">
						<div v-if="row.status <= 0">
							<a @click="openNewModal(row.id)">编辑</a>
						</div>
						<div  v-if="row.status <= 0">
							<a @click="del(row, 'Cancel reception', index)">取消</a>
						</div>
						<div>
							<a @click="openDetailModal(row.id)">查看詳情</a>
						</div>
					</template> -->
				</Table>
				<div class="acea-row row-right page">
					<Page :total="total" :current.sync="formValidate.page" @on-change="pageChange"
						:page-size="formValidate.limit" />
				</div>
			</div>
		</Card>

		<add-access-customer ref="addAccessCustomer" :customer-id="currentCustomerId"
			:visible.sync="newSelectGoodVisible" @success="handleSuccess"></add-access-customer>
		<access-customer-detail ref="accessCustomerDetail" :customer-id="currentCustomerId"
			:visible.sync="detailAccessVisible" @success="handleDetailSuccess"></access-customer-detail>
	</div>
</template>

<script>
	import exportExcel from '@/utils/newToExcel.js';
	import zhCNiView from 'view-design/dist/locale/zh-CN';
	import addAccessCustomer from '../components/addAccessCustomer';
	import accessCustomerDetail from '../components/accessCustomerDetail';
	import {
		customerAccessListApi,
		accessDelete
	} from "@/api/storeCustomer";
	import timeOptions from '@/utils/timeOptions2';
	export default {
		name: 'bill',
		components: {
			addAccessCustomer,
			accessCustomerDetail
		},
		data() {
			return {
				total: 0,
				loading: false,
				productShow: false,
				newSelectGoodVisible: false,
				detailAccessVisible: false,
				currentCustomerId: null,
				tab: '1',
				customLocale: zhCNiView,
				tableList: [],
				productList: [],
				options: timeOptions,
				productSearchsData: {
					store_name: "",
					type: 1,
					activity_id: 0,
					page: 1,
					limit: 15,
				},
				formValidate: {
					customer_name: "",
					time: '',
					status: "",
					page: 1,
					limit: 15,
				},
				timeVal: [],
				fromList: {
					title: '选择时间',
					custom: true,
					fromTxt: [{
							text: '全部',
							val: ''
						},
						{
							text: '昨天',
							val: 'yesterday'
						},
						{
							text: '今天',
							val: 'today'
						},
						{
							text: '本周',
							val: 'week'
						},
						{
							text: '本月',
							val: 'month'
						},
						{
							text: '本季度',
							val: 'quarter'
						},
						{
							text: '本年',
							val: 'year'
						},
					],
				},
			};
		},
		computed: {
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			labelPosition() {
				return this.isMobile ? 'top' : 'left';
			},
			columns() {
				return [{
						title: "ID",
						key: "id",
						width: 80,
					},
					{
						title: $t('page.customer.customer_name'),
						key: "customer_name",
						minWidth: 100,
					},
					{
						title: $t('page.customer.access_time'),
						key: "visit_time_str",
						minWidth: 100,
					},
					{
						title: $t('page.stock.status'),
						slot: "status",
						minWidth: 100,
					},
					{
						title: $t('page.stock.note'),
						key: 'remarks',
						minWidth: 500, // 适当调整宽度
						render: (h, {
							row
						}) => {
							return h(
								'Tooltip', {
									props: {
										content: '', // 不使用默认 content，改为 slot
										placement: 'top',
									},
									scopedSlots: {
										content: () => h(
											'div', {
												style: {
													maxHeight: '200px', // 限制高度
													overflowY: 'auto',
													maxWidth: '600px', // 可选：防止一行过长
													whiteSpace: 'pre-wrap', // 换行
												}
											},
											row.remarks || $t('page.product.no_data')
										)
									}
								},
								[h('span', {
									style: {
										display: 'inline-block',
										maxWidth: '500px',
										whiteSpace: 'nowrap',
										overflow: 'hidden',
										textOverflow: 'ellipsis',
									}
								}, row.remarks || $t('page.product.no_data'))]
							)
						}
					},
					{
						title: $t('page.activity.operation'),
						slot: "action",
						minWidth: 150,
					},
				]
			}
		},
		watch: {
			tab: {
				handler() {
					this.formValidate.page = 1;
					this.getList();
				},
				immediate: true,
			},
		},
		methods: {
			del(row, tit, num) {
				let delfromData = {
					title: $t('page.customer.cancel_reception'),
					num: num,
					url: `store_customer/access_del/${row.id}`,
					method: "DELETE",
					ids: "",
					info: $t('page.customer.cancel_reception_confirm'),
				};

				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg);
						this.tableList.splice(num, 1);
						if (!this.tableList.length) {
							this.formValidate.page =
								this.formValidate.page == 1 ? 1 : this.formValidate.page - 1;
						}
						this.getDataList();
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			handleSuccess() {
				this.getList();
			},
			handleDetailSuccess() {
				this.getList();
			},
			//添加产品
			addProduct() {
				this.productShow = true
				this.getProductList();
			},
			submitProduct() {
				this.productShow = false
			},
			openNewModal(id) {
				this.currentCustomerId = id; // 设置当前客户id
				this.newSelectGoodVisible = true;
			},
			openDetailModal(id) {
				this.currentCustomerId = id; // 设置当前客户id
				this.detailAccessVisible = true;
			},
			getProductList() {
				this.loading = true;
				this.productList = [];
				this.productSearchsData.activity_id = this.activityId
				activityProductListInfo(this.productSearchsData).then((res) => {
					res.data.list.forEach(item => {
						let stock = 0
						let skuList = []
						item.store_product_attr_value.forEach(attrItem => {
							stock += attrItem.stock
							skuList.push({
								product_id: item.id,
								id: attrItem.id,
								image: attrItem.image,
								price: attrItem.price,
								stock: attrItem.stock,
								store_name: item.store_name,
								suk: attrItem.suk,
								sku: attrItem.code,
								product_stock_info: attrItem.product_stock_info,
								activity_price: 0,
								activity_stock: 0,
							})
						})
						// if(stock == 0 || fo)
						this.productList.push({
							product_id: item.id,
							id: item.id,
							image: item.image,
							price: item.price,
							stock: stock,
							store_name: item.store_name,
							skuList: skuList,
							is_disable: item.is_disable,
						})
					})
					this.total = res.data.count;
					this.loading = false;
					this.initActivityStockData(); // 初始化活动库存数据
				}).catch((err) => {
					this.loading = false;
					this.$Message.error(err.msg);
				})
			},
			// 参与活动
			joinIn(row) {
				// console.log(this.roterPre + '/activityInfo/' + row.id)
				this.$router.push({
					path: '/supplier/activity/activityInfo/' + row.id
				})
			},
			allReset() {
				this.formValidate.name = '';
				this.formValidate.phone = '';
				this.getList();
			},
			//搜索
			search() {
				this.formValidate.page = 1;
				this.getList();
			},
			onClickTab(e) {
				this.tab = e;
			},
			// 时间格式化方法
			// 原生 JS 格式化
			formatTimeNative(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			getList() {
				this.loading = true;

				let data = {
					join_type: this.tab,
					date: this.formValidate.time,
					customer_name: this.formValidate.customer_name,
					page: this.formValidate.page,
					limit: this.formValidate.limit,
				};

				if (this.formValidate.status != "" && this.formValidate.status != undefined) {
					data.status = this.formValidate.status
				}

				customerAccessListApi(data)
					.then(async (res) => {
						let data = res.data;
						this.tableList = data.list;
						this.total = res.data.count;
						this.loading = false;
					})
					.catch((res) => {
						this.loading = false;
						this.$Message.error(res.msg);
					});
			},
			// 选择时间
			selectChange(tab) {
				this.formValidate.page = 1;
				this.formValidate.data = tab;
				this.timeVal = [];
				this.getList();
			},

			// 具体日期
			onchangeTime(e) {
				this.timeVal = e;
				this.formValidate.date = this.timeVal;
				console.log(this.formValidate.date)
				this.getList();
			},
			//分页
			pageChange(status) {
				this.formValidate.page = status;
				this.getList();
			},
			// 账单详情
			Info(row) {
				this.$refs.commission.modals = true;
				this.$refs.commission.getList(row.ids);
			},
			//下载
			async download(row) {
				let [th, filekey, data, fileName] = [
					[],
					[],
					[], ''
				];
				let excelData = {
					ids: row.ids,
					page: 1
				};
				let lebData = await this.getExcelData(excelData);
				if (!fileName) {
					fileName = lebData.filename;
				}
				if (!filekey.length) {
					filekey = lebData.filekey;
				}
				if (!th.length) {
					th = lebData.header;
				}
				data = [...data, ...lebData.export];
				exportExcel(th, filekey, fileName, data);
			},
			getExcelData(excelData) {
				return new Promise((resolve) =>
					exportfundRecordApi(excelData).then((res) => resolve(res.data))
				);
			},
		},
	};
</script>

<style scoped lang="less">
	/deep/.ivu-page-header,
	/deep/.ivu-tabs-bar {
		border-bottom: 1px solid #ffffff;
	}

	/deep/.ivu-card-body {
		padding: 0;
	}

	/deep/.ivu-tabs-nav {
		height: 45px;
	}

	/deep/.ivu-tabs-bar {
		margin-bottom: 0px !important;
		border-bottom: 1px solid #e9e9e9 !important;
	}

	.tabbox {
		padding: 16px 20px 0px;
	}

	.box {
		padding: 20px;
		padding-bottom: 1px;
	}

	.tablebox {
		margin-top: 15px;
		padding-bottom: 10px;
	}

	.btnbox {
		padding: 20px 0px 0px 30px;

		.btns {
			width: 99px;
			height: 32px;
			background: #1890ff;
			border-radius: 4px;
			text-align: center;
			line-height: 32px;
			color: #ffffff;
			cursor: pointer;
		}
	}

	.table {
		padding: 0px 30px 15px 30px;
	}

	.search {
		width: 86px;
		height: 32px;
		background: #1890ff;
		border-radius: 4px;
		text-align: center;
		line-height: 32px;
		font-size: 13px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #ffffff;
		cursor: pointer;
	}

	.reset {
		width: 86px;
		height: 32px;
		border-radius: 4px;
		border: 1px solid rgba(151, 151, 151, 0.36);
		text-align: center;
		line-height: 32px;
		font-size: 13px;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		font-weight: 500;
		color: #515a6e;
		// background: #2D8CF0;

		cursor: pointer;
	}

	.ivu-form-item-label {
		width: 40px;
		;
	}

	.address-link {
		color: #2d8cf0;
		text-decoration: underline;
		cursor: pointer;
		transition: color 0.3s;
	}

	.address-link:hover {
		color: #57a3f3;
		text-decoration: none;
	}

	.gray-tab {
		color: #999 !important;
	}
</style>